package com.studyroom.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.Result;
import com.studyroom.entity.Order;
import com.studyroom.entity.OrderItem;
import com.studyroom.service.OrderService;
import com.studyroom.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orders")
public class AppOrderController {

    private static final Logger log = LoggerFactory.getLogger(AppOrderController.class);

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping
    public Result<?> create(@RequestBody Map<String, Object> params,
                          @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            
            // 获取订单项列表
            List<Map<String, Object>> itemMaps = (List<Map<String, Object>>) params.get("items");
            List<OrderItem> items = itemMaps.stream().map(map -> {
                OrderItem item = new OrderItem();
                item.setSnackId(Long.valueOf(map.get("snackId").toString()));
                item.setQuantity((Integer) map.get("quantity"));
                return item;
            }).collect(Collectors.toList());
            
            String deliveryLocation = (String) params.get("deliveryLocation");
            String deliveryTime = (String) params.get("deliveryTime");
            
            orderService.createOrder(username, items, deliveryLocation, 
                LocalDateTime.parse(deliveryTime));
            return Result.success("下单成功");
        }
        return Result.error("下单失败");
    }

    @GetMapping("/my")
    public Result<Page<Order>> getMyOrders(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            Page<Order> orders = orderService.getMyOrders(username, status, new Page<>(page, size));
            
            // 添加日志
            if (!orders.getRecords().isEmpty()) {
                Order firstOrder = orders.getRecords().get(0);
                log.debug("Sample order data:");
                log.debug("- createdAt: {}", firstOrder.getCreatedAt());
                log.debug("- createdAt type: {}", firstOrder.getCreatedAt().getClass().getName());
                log.debug("- createdAt toString: {}", firstOrder.getCreatedAt().toString());
                if (firstOrder.getCreatedAt() instanceof LocalDateTime) {
                    LocalDateTime ldt = (LocalDateTime) firstOrder.getCreatedAt();
                    log.debug("- year: {}, month: {}, day: {}, hour: {}, minute: {}, second: {}", 
                        ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(),
                        ldt.getHour(), ldt.getMinute(), ldt.getSecond());
                }
            }
            
            return Result.success(orders);
        }
        return Result.error("获取订单列表失败");
    }

    @PutMapping("/{id}/cancel")
    public Result<?> cancel(@PathVariable Long id,
                          @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            orderService.cancelOrder(username, id);
            return Result.success("取消成功");
        }
        return Result.error("取消失败");
    }
} 